/*******************************************************************

    Author: Xiao
    Date: 2022/4/1 10:28

*******************************************************************/
package websocket

import (
	"github.com/gorilla/websocket"
	"mcr/pkg/logs"
	"time"
)

const (
	// 用户连接超时时间
	heartbeatExpirationTime = 6 * 60
)

// 用户连接
type Client struct {
	Addr          string          // 客户端地址
	Ticket        string          // socket标识
	Socket        *websocket.Conn // 用户连接
	UserId        string          // 用户Id，用户登录以后才有
	RoomId        int             // 用户Id，用户登录以后才有
	FirstTime     uint64          // 首次连接时间
	HeartbeatTime uint64          // 用户上次心跳时间
}

// 初始化
func NewClient(socket *websocket.Conn, addr, userId, ticket string, RoomId int) {
	firstTime := uint64(time.Now().Unix())
	client := &Client{
		Addr:          addr,
		Socket:        socket,
		UserId:        userId,
		RoomId:        RoomId,
		FirstTime:     firstTime,
		HeartbeatTime: firstTime,
		Ticket:        ticket,
	}
	SCM.Register <- client
	// 断开连接时的处理
	client.Socket.SetCloseHandler(func(code int, text string) error {
		SCM.Unregister <- client
		return nil
	})
	// 开启协程监听客户端发送的信息
	go func() {
		for {
			t, c, _ := client.Socket.ReadMessage()
			switch string(c) {
			case "bye":
				logs.Log.Infof("用户:%v(%s)房号:%d主动断开链接", client.UserId, client.Addr, client.RoomId)
				client.UnConnectSocket()
				SCM.Unregister <- client
				return
			}
			if t == -1 {
				return
			}
		}
	}()
	return
}
